/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package netoppiggy_client;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;
import netoppiggy_interface.FormChat;

/**
 *
 * @author
 * Dai
 */
public class ClientThread implements Runnable {

    Socket m_clientSocket;
    boolean m_bRunThread = true;
    BufferedReader m_in = null;
    PrintWriter m_out = null;
    JTextArea _textArea;
    FormChat _formChat;
    public ClientMainForm _frmChat;

    public void sendMessage(String msg) {
        m_out.println(msg);
    }

    public String receiveMessage() {
        try {
            return m_in.readLine();
        } catch (IOException ex) {
            return null;
        }
    }

    ClientThread(Socket s, FormChat frm) {
        this._formChat = frm;
        m_clientSocket = s;

        try {
            m_in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
            m_out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
        } catch (IOException ex) {
            Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void receiveFile(File file) throws IOException {
        try {
            byte[] b = new byte[1024];
            int len = 0;
            int bytcount = 1024;
            FileOutputStream inFile = new FileOutputStream(file);
            InputStream is = this.m_clientSocket.getInputStream();
            BufferedInputStream in2 = new BufferedInputStream(is, 1024);

            BufferedReader in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));

            while ((len = in2.read(b, 0, 1024)) != -1) {
                bytcount = bytcount + 1024;
                inFile.write(b, 0, len);
            }
            System.out.println("Bytes Writen : " + bytcount);

            in2.close();
            inFile.close();
        } catch (IOException ex) {
            Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        // Obtain the input stream and the output stream for the socket 
        // A good practice is to encapsulate them with a BufferedReader 
        // and a PrintWriter as shown below. 
        BufferedReader in = null;
        //PrintWriter out = null;

        // Print out details of this connection 
        // System.out.println("Accepted Client : ID - " + m_clientID + " : Address - "
        //   + m_clientSocket.getInetAddress().getHostName());

        try {
            in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
            //out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));

            // At this point, we can read for input and reply with appropriate output. 

            // Run in a loop until m_bRunThread is set to false 
            while (m_bRunThread) {
                // read incoming stream 
                String clientCommand = in.readLine();

                String[] arrSrt = clientCommand.split("--");
                if (arrSrt[0].equals("sendfile")) {
                    String fileName = arrSrt[1];
                    String path = "d:/temp/" + fileName;
                    receiveFile(new File(path));
                } else {

                    String text = "\nServer: " + clientCommand;
                    //text += "\nClient : " + clientCommand;
                    //_textArea.append(text);
                    this._formChat.appendText("\n" + clientCommand);
                    //System.out.println("Client Says :" + clientCommand);


                    if (clientCommand.equalsIgnoreCase("quit")) {
                        // Special command. Quit this thread 
                        m_bRunThread = false;
                        //System.out.print("Stopping client thread for client : " + m_clientID);
                        //} else {
                        // Echo it back to the client. 
                        //out.println(clientCommand);
                        //out.flush();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Clean up 
            try {
                in.close();
                //out.close();
                m_clientSocket.close();
                System.out.println("...Stopped");
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}
